﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using Dac.DAL;
using Dac.DAL.Repositories;
using Dac.Entities;
using Dac.Code;

namespace Dac.Admin
{
    public partial class ProductDetail : System.Web.UI.Page
    {
        private string ProductPath
        {
            get
            {
                return MapPath("~/Files/Products/");
            }
        }
        private string ProductPathUrl
        {
            get
            {
                return ResolveClientUrl("~/Files/Products/");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ProductId == -1)
                lblTitle.Text = "Новый товар";
            else
                lblTitle.Text = "Карточка товара";

            if (!IsPostBack)
            {
                LoadProduct();
                if (Session["ShowSaved"] != null)
                {
                    string script = string.Format("alert('{0}'); ", "Товар сохранен!");
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", script, true);
                    Session["ShowSaved"] = null;
                }
            }
        }

        public void LoadProduct()
        {
            if (ProductId == -1)
                return;
            
            Product item = null;
            using (var repo = RepositoryFactory.ResolveRepository<ProductRepository>())
            {
                item = repo.Find(ProductId);
            }

            if (item == null)
            {
                string script = string.Format("alert('{0}'); ", "Товар не найден!");
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", script, true);
                return;
            }

            txtProductNameRu.Text = item.ProductNameRu;
            txtProductNameEn.Text = item.ProductNameEn;
            txtProductDescRu.Text = HttpUtility.HtmlDecode(item.ProductDescRu);
            txtProductDescEn.Text = HttpUtility.HtmlDecode(item.ProductDescEn);
            txtPrice.Text = item.Price.ToString();
            chkIsShow.Checked = item.IsShow;
            chkOutStock.Checked = item.OutStock;

            if (!string.IsNullOrEmpty(item.PreviewImage))
                imgPreviewImage.ImageUrl = ProductPathUrl + ProductId.ToString() + "/" + item.PreviewImage;
            /*else
                imgPreviewImage.Visible = false;*/

            if (!string.IsNullOrEmpty(item.MainImage))
                imgMainImage.ImageUrl = ProductPathUrl + ProductId.ToString() + "/" + item.MainImage;
            /*else
                imgMainImage.Visible = false;*/

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Product item = new Product();
            Product itemOld = new Product();

            using (var repo = RepositoryFactory.ResolveRepository<ProductRepository>())
            {
                itemOld = repo.Find(ProductId);
            }

            item.ProductNameRu = txtProductNameRu.Text;
            item.ProductNameEn = txtProductNameEn.Text;
            item.ProductDescRu = Request.Form["ctl00$MainContent$txtProductDescRu"]; //txtProductDescRu.Text;
            item.ProductDescEn = Request.Form["ctl00$MainContent$txtProductDescEn"];//txtProductDescEn.Text;

            if (fuMainImage.HasFile)
                item.MainImage = Transliteration.Front(fuMainImage.FileName);
            if (fuPreviewImage.HasFile)
                item.PreviewImage = Transliteration.Front(fuPreviewImage.FileName);
            
            item.Price = Convert.ToInt32(txtPrice.Text);
            item.IsShow = chkIsShow.Checked;
            item.OutStock = chkOutStock.Checked;
            item.ProductId = ProductId;

            using (var repo = RepositoryFactory.ResolveRepository<ProductRepository>())
            {
                if (ProductId == -1)
                    repo.Insert(item);
                else
                    repo.Update(item);
            }

            string imagePath = Path.Combine(ProductPath, item.ProductId.ToString());
            if ((fuMainImage.HasFile) || (fuPreviewImage.HasFile))
                if (!Directory.Exists(imagePath))
                    Directory.CreateDirectory(imagePath);

            if (fuMainImage.HasFile)
            {
                fuMainImage.SaveAs(Path.Combine(imagePath, item.MainImage));
                if ((itemOld != null) && (!string.IsNullOrEmpty(itemOld.MainImage)) && (!item.MainImage.Equals(itemOld.MainImage)))
                    if (File.Exists(Path.Combine(imagePath, itemOld.MainImage)))
                        File.Delete(Path.Combine(imagePath, itemOld.MainImage));
            }
            if (fuPreviewImage.HasFile)
            {
                fuPreviewImage.SaveAs(Path.Combine(imagePath, item.PreviewImage));
                if ((itemOld != null) && (!string.IsNullOrEmpty(itemOld.PreviewImage)) && (!item.PreviewImage.Equals(itemOld.PreviewImage)))

                    if (File.Exists(Path.Combine(imagePath, itemOld.PreviewImage)))
                        File.Delete(Path.Combine(imagePath, itemOld.PreviewImage));
            }
            
            Session["ShowSaved"] = true;
            Response.Redirect("ProductDetail.aspx?pid=" + item.ProductId.ToString());
        }

        public int ProductId
        {
            get
            {
                int result = -1;
                if (!string.IsNullOrEmpty(Request.QueryString["pid"]))
                    result = Convert.ToInt32(Request.QueryString["pid"]);
                return result;
            }
        }
    }
}